package action;

import io.impl.FileCreaterImpl;

import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Comparator;
import java.util.List;

import network.TCPServer;
import comparetor.CustomerComparetorByBirth;
import comparetor.CustomerComparetorById;
import pojo.Command;
import pojo.Customer;
import processor.DataProcessor;
import processor.impl.DataProcessorImpl;
import scanner.DataScanner;
import scanner.impl.DataScannerImpl;

public class DataProcessAction {
	private Comparator<Customer> comparator;
	private DataProcessor dp;
	private DataScanner scanner;
	private String format;
	private List<Customer> list;

	public void action() throws Exception {
		format = "line";
		DataScanner scanner = new DataScannerImpl(new FileInputStream(
				"data.txt"));
		// /分析和排除错误后得到的对象数组
		this.list = scanner.scann();
		
	}

	/***
	 * 根据命令，进行处理，最终得到反馈结果StringBuilder对象
	 * @param command 客户端的命令
	 * @return 处理后得到的结果
	 */
	public StringBuilder createServerAnswer(Command command) {
		String commandHead = command.getHead();
		String dataType = command.getOption();
		String orderBy = command.getOrderBy();
		dp = new DataProcessorImpl(list, dataType);
		
		if (orderBy == "id") {
			this.comparator = new CustomerComparetorById();
		} else if (orderBy.equals("birth")) {
			this.comparator = new CustomerComparetorByBirth();
		}
		
		///得到批处理后的反馈信息
		StringBuilder sb = dp.process(comparator);
		switch (commandHead) {
		case "L":
			// / 根据情况，进行数据批处理（排序和打印等）
			return sb;
		case "C":
			// //创建文件，并存储
			if(dataType.equals("xml")){
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileCreaterImpl().createFile("datas.xml")));
				try {
					bw.write(sb.toString());
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}else if(dataType.equals("line")){
				BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileCreaterImpl().createFile("datas.txt")));
				try {
					bw.write(sb.toString());
				} catch (IOException e) {
					e.printStackTrace();
				} finally{
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			sb = new StringBuilder("Creata file success！\r\nPlease input command --->  ");
			break;
		default:
			sb = new StringBuilder("Please input command --->  ");
			break;
		}
		return sb;
	}

}
